package com.wl2o2o.javau8g;

import java.util.concurrent.*;

/**
 * 如何让 Java 的线程池顺序执行任务
 * @Author <a href="https://github.com/wl2o2o">程序员CSGUIDER</a>
 * @From <a href="https://wl2o2o.github.io">CSGUIDER博客</a>
 * @CreateTime 2024/4/23
 */

public class ThreadPool {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 方法一：创建一个单线程线程池
        // ExecutorService executor = Executors.newSingleThreadExecutor();
        //
        // // 使用submit方法提交任务，并等待执行完成
        // for (int i = 0; i < 4; i++) {
        //     final int index = i;
        //     executor.submit(() -> {
        //         System.out.println("Thread: " + (char)('A' + index));
        //     });
        //     try {
        //         Thread.sleep(1000);
        //     } catch (InterruptedException e) {
        //         e.printStackTrace();
        //     }
        // }
        // // 方法二：使用有依赖关系的任务调度方式，
        //   stpe = Executors.newScheduledThreadPool(1);
        // ScheduledFuture<?> future =
        //         stpe.schedule(() -> System.out.println("Thread: A"), 0, TimeUnit.SECONDS);
        // ScheduledFuture<?> future1 =
        //         stpe.schedule(() -> System.out.println("Thread: B"), (long) future.get(), TimeUnit.SECONDS);
        // ScheduledFuture<?> future2 =
        //         stpe.schedule(() -> System.out.println("Thread: C"), (long) future1.get(), TimeUnit.SECONDS);
        // ScheduledFuture<?> future3 =
        //         stpe.schedule(() -> System.out.println("Thread: D"), (long) future2.get(), TimeUnit.SECONDS);
        // stpe.shutdown();
        // System.out.println("Thread: Done");
        // // 方法二：使用ExecutorService + completionService
        // ExecutorService executorService = Executors.newFixedThreadPool(4);
        // ExecutorCompletionService<Object> completionService = new ExecutorCompletionService<>(executorService);
        // completionService.submit(() -> {
        //     System.out.println("Thread: A");
        //     return 'A';
        // });
        // completionService.submit(() -> {
        //     System.out.println("Thread: B");
        //     return 'B';
        // });
        // completionService.submit(() -> {
        //     System.out.println("Thread: C");
        //     return 'C';
        // });
        // completionService.submit(() -> {
        //     System.out.println("Thread: D");
        //     return 'D';
        // });
        // // 按完成顺序获取结果并打印
        // for (int i = 0; i < 2; i++) {
        //     Future<Object> result = completionService.take();
        //     char character = (char) result.get(); // 获取并忽略返回值，实际关注的是打印顺序
        //     System.out.println("Completed task returned character: " + character);
        // }
        //
        // // 关闭线程池
        // executorService.shutdown();


    }

}
